/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} inorder
 * @param {number[]} postorder
 * @return {TreeNode}
 */
var buildTree = function(inorder, postorder) {
    let count = postorder.length
    const iter = function(left, right) {
        if(count < 0) return
        if(left === right) {
            return new TreeNode(inorder[left])
        }
        let index
        count--
        for(let i = 0; i < right; i++) {
            if(inorder[i] === postorder[count]) {
                index = i
            }
        }
        const node = new TreeNode(postorder[count])
        node.right = iter(left, index - 1)
        node.left = iter(index + 1, right)
        return node
    }
    return iter(0, inorder.length)
};